package com.vegetable.modules.controller.baseData;

import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.baseData.AddressBook;
import com.vegetable.modules.entity.baseData.InvoiceInfo;
import com.vegetable.modules.service.baseData.IAddressBookService;
import com.vegetable.modules.service.baseData.impl.BaiduServiceImpl;
import com.vegetable.modules.service.baseData.impl.QiniuServiceImpl;
import com.vegetable.modules.service.finance.IInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/ocr")
@AllArgsConstructor
@Api(value = "图片", tags = "图片")
public class OCRController {
    @Autowired
    private BaiduServiceImpl baiduService;
    @Autowired
    private IInvoiceService invoiceService;
    @Autowired
    private QiniuServiceImpl qiniuService;
    @Autowired
    private IAddressBookService addressBookService;

    @PostMapping("/vatInvoice")
    @ApiOperation(value = "识别增值税发票", notes = "上传图片")
    public R uploadImage(@RequestParam("file") MultipartFile file, @RequestParam(value = "accountId", required = true) Long abId) throws IOException {
        String base64 = Base64.getEncoder().encodeToString(file.getBytes());
        if (true) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        AddressBook fa = addressBookService.getById(abId);
        if(Objects.isNull(fa)){
            throw new RuntimeException("账户不存在，请确认后重试.");
        }
        String orderImage = qiniuService.upload(file, "invoice");
        InvoiceInfo invoiceResult = baiduService.vatInvoice(base64);
        invoiceResult.setOrderImage(orderImage);
        invoiceResult.setAbId(abId);
        invoiceResult.setAbName(fa.getNoteName());
        invoiceService.saveInvoice(invoiceResult);
        String sellerBankNo = invoiceResult.getSellerBankAccount();
        // 同步更新客户的银行卡信息
        // 银行卡号现在通过BankCard实体管理，此处逻辑已移除
        return R.data(invoiceResult);
    }

    @PostMapping("/financeRecognise")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    public R financeRecognise(@RequestParam("file") MultipartFile file) throws IOException {
        String base64 = Base64.getEncoder().encodeToString(file.getBytes());
        if (true) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        baiduService.financeRecognise(base64);
        return R.data("");
    }
}
